<template>
  <div class="energy_consume">
    <div class="top_query">
      <div class="tabs">
        <px-radio-group v-model="queryTypeParams.energyType" class="tabSwitch" @change="handleChangeTypeFn">
          <px-radio-button :label="1">电</px-radio-button>
          <px-radio-button :label="2">自来水</px-radio-button>
          <px-radio-button :label="16">天然气</px-radio-button>
          <px-radio-button :label="3">蒸汽</px-radio-button>
          <px-radio-button :label="7">热水</px-radio-button>
          <px-radio-button :label="9">CDA</px-radio-button>
          <px-radio-button :label="10">N₂</px-radio-button>
          <px-radio-button :label="11">H₂</px-radio-button>
          <px-radio-button :label="12">O₂</px-radio-button>
          <px-radio-button :label="13">Ar</px-radio-button>
          <px-radio-button :label="14">He</px-radio-button>
          <px-radio-button :label="15">CO₂</px-radio-button>
          <!-- <px-radio-button :label="4">柴油</px-radio-button> -->
        </px-radio-group>
      </div>
      <px-form ref="queryRef" class="custom-form-ui inspection-form" :model="queryParams" :inline="true" label-width="100px">
        <px-form-item label="时间">
          <px-date-picker v-model="queryParams.dateRangeItem" type="year" :clearable="false" placeholder="请选择" format="YYYY" value-format="YYYY" />
        </px-form-item>
        <px-button type="primary" icon="" @click="handleQuery">搜索</px-button>
        <px-button icon="" @click="resetQuery">重置</px-button>
      </px-form>
    </div>
    <div class="mid-bord">
      <rowBord
        :key="midKey + 10"
        title="年度费用趋势"
        :unit="getUnit"
        :actualDataList="actualDataList"
        :predictDataList="predictDataList"
        :width="1300"
        :height="167"
        :isCurrentYear="isCurrentYear"
      />
    </div>
    <div class="btn-con">
      <div class="btn-bord">
        <div class="rightBox">
          <px-button v-if="annualOverview" v-has="'ALL_ENERGY_COST_PREDICT_DOWNLOAD'" @click="handleDown('year')">
            导出<px-icon class="px-icon--right">
              <Download />
            </px-icon>
          </px-button>
        </div>
        <bordBarchartYear
          v-if="annualOverview"
          :key="midKey"
          title="年度总览"
          :unit="getUnit"
          :dataList="annualOverview"
          :width="642"
          :height="505"
          :options="yearOptions"
          :timeFrame="queryParams.dateRangeItem"
        />
        <px-empty v-else :image-size="100" />
      </div>
      <!-- 选择月份 -->
      <!-- <div class="btn-bord">
        <div class="rightBox">
          <px-select v-model="queryParams.month" placeholder="选择月份" class="selectMonth" @change="changeMonth">
            <px-option v-for="item in monthsArray" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
          <px-button v-if="monthlyDetails" @click="handleDown('month')">
            导出<px-icon class="px-icon--right">
              <Download />
            </px-icon>
          </px-button>
        </div>
        <bordBarchartMonth
          v-if="monthlyDetails"
          :key="midKey - 10"
          title="月度明细"
          :unit="getUnit"
          :dataList="monthlyDetails"
          :width="642"
          :height="167"
          :options="monthOptions"
          :timeFrame="queryParams.dateRangeItem"
          :month="queryParams.month"
        />
        <px-empty :image-size="100" v-else />
      </div> -->
    </div>
    <!-- <div>
      <EnergyConsumeRank />
    </div> -->
  </div>
</template>
<script setup lang="ts">
defineOptions({
  name: "ALL_ENERGY_PREDICT_NEED"
});
import { ref, getCurrentInstance, onMounted, computed } from "vue";
import type { UtilsEChartsOption } from "@pureadmin/utils";
import { queryDictData } from "@/api/common";
import rowBord from "./components/rowBord.vue";
import bordBarchartYear from "./components/bordBarchartYear.vue";
import { getCostPredictData } from "@/api/energy/predictApi";
// import EnergyConsumeRank from "@/views/common/energy/components/EnergyConsumeRank.vue";
import { Download } from "@px-ui/icons-vue";

const { proxy }: any = getCurrentInstance();

const midKey = ref(Date.now());

const systemList = ref<any>([]);

const monthOptions = ref<UtilsEChartsOption>({});
const yearOptions = ref<UtilsEChartsOption>({});

const currentYear = new Date().getFullYear();
const monthsArray = ref(Array.from({ length: 12 }, (_, index) => ({ value: index + 1, label: `${index + 1}月` })));
let isCurrentYear = ref(false);
const getUnit = computed(() => {
  // switch (queryTypeParams.value.energyType) {
  //   case 1:
  //     return "MKH"; // 电
  //   case 2:
  //     return "m³"; // 水
  //   case 3:
  //     return "t"; // 蒸汽
  //   case 7:
  //     return "t"; // 热水
  //   case 4:
  //     return "t"; // 柴油
  //   case 5:
  //     return "Nm³"; // 大宗气
  //   case 6:
  //     return "Nm³"; // 大宗气
  //   case 9:
  //     return "Nm³"; // 大宗气
  //   case 10:
  //     return "Nm³"; // 大宗气
  //   case 11:
  //     return "Nm³"; // 大宗气
  //   case 12:
  //     return "Nm³"; // 大宗气
  //   case 13:
  //     return "Nm³"; // 大宗气
  //   case 14:
  //     return "Nm³"; // 大宗气
  //   case 15:
  //     return "Nm³"; // 大宗气

  //   default:
  //     return "MKH";
  // }
  return "万元";
});

const getIcon = computed(() => {
  switch (queryTypeParams.value.energyType) {
    case 1:
      return "icon_electricity"; // 电
    case 2:
      return "icon_water"; // 水
    case 3:
      return "icon_steam"; // 蒸汽
    case 7:
      return "icon_hot_water"; // 热水
    case 4:
      return "icon_diesel"; // 柴油
    case 5:
      return "icon_gas"; // 大宗气
    case 6:
      return "icon_ng"; // 天然气
    case 9:
      return "icon_cda"; // 天然气
    case 10:
      return "icon_n2"; // 天然气
    case 11:
      return "icon_h2"; // 天然气
    case 12:
      return "icon_o2"; // 天然气
    case 13:
      return "icon_ar"; // 天然气
    case 14:
      return "icon_he"; // 天然气
    case 15:
      return "icon_co2"; // 天然气

    default:
      return "icon_electricity";
  }
});

// 年度能耗趋势--实际能耗趋势
const actualDataList = ref<any>([
  {
    name: `${currentYear - 2}`,
    icon: getIcon,
    unit: getUnit,
    valueFormat: null,
    yoy: null
  },
  {
    name: `${currentYear - 1}`,
    icon: getIcon,
    unit: getUnit,
    valueFormat: null,
    yoy: null
  },
  {
    name: `${currentYear}`,
    icon: getIcon,
    unit: getUnit,
    valueFormat: null,
    yoy: null
  },
  {
    name: `${currentYear + 1}`,
    icon: getIcon,
    unit: getUnit,
    valueFormat: null,
    yoy: null
  }
]);
// 年度能耗趋势---预测能耗趋势
const predictDataList = ref<any>([
  {
    name: `${currentYear - 2}`,
    icon: getIcon,
    unit: getUnit,
    valueFormat: null,
    yoy: null
  },
  {
    name: `${currentYear - 1}`,
    icon: getIcon,
    unit: getUnit,
    valueFormat: null,
    yoy: null
  },
  {
    name: `${currentYear}`,
    icon: getIcon,
    unit: getUnit,
    valueFormat: null,
    yoy: null
  },
  {
    name: `${currentYear + 1}`,
    icon: getIcon,
    unit: getUnit,
    valueFormat: null,
    yoy: null
  }
]);
// 年度总览
const annualOverview = ref(null);
// 月度明细
const monthlyDetails = ref(null);
type itemStyleType = {
  [key: string]: string;
};

interface dataType {
  name: string;
  value: number;
  itemStyle?: itemStyleType;
}

let getMinYMaxY = (data: object) => {
  let maxCoorY = data.kwhCoordinate.reduce((pre, cur) => {
    if (Number(cur)) {
      return Number(cur) > Number([pre]) ? Number(cur) : Number(pre);
    } else {
      return Number(pre);
    }
  }, 0);
  let minCoorY = data.kwhCoordinate.reduce((pre, cur) => {
    if (Number(cur)) {
      return Number(cur) < Number([pre]) && Number(cur) ? Number(cur) : Number(pre);
    } else {
      return Number([pre]);
    }
  }, maxCoorY);
  let maxPredictY = data.kwhPredictCoordinate.reduce((pre, cur) => {
    if (Number(cur)) {
      return Number(cur) > Number([pre]) ? Number(cur) : Number(pre);
    } else {
      return Number(pre);
    }
  }, 0);
  let minPredictY = data.kwhPredictCoordinate.reduce((pre, cur) => {
    if (Number(cur)) {
      return Number(cur) < Number([pre]) && Number(cur) ? Number(cur) : Number(pre);
    } else {
      return Number(pre);
    }
  }, maxPredictY);
  let maxY = maxCoorY > maxPredictY ? maxCoorY : maxPredictY;
  let minY;
  if (minCoorY > 0) {
    if (minPredictY > 0) {
      minY = minCoorY < minPredictY ? minCoorY : minPredictY;
    } else {
      minY = minCoorY;
    }
  } else {
    minY = minPredictY;
  }
  maxY = (maxY * 1.2).toFixed(2);
  minY = (minY * 0.8).toFixed(2);
  let maxrcY = data.radioCoordinate.reduce((pre, cur) => {
    if (Number(cur)) {
      return Number(cur) > Number([pre]) ? Number(cur) : Number(pre);
    } else {
      return Number(pre);
    }
  }, 0);
  let minrcY = data.radioCoordinate.reduce((pre, cur) => {
    if (Number(cur)) {
      return Number(cur) < Number([pre]) && Number(cur) ? Number(cur) : Number(pre);
    } else {
      return Number([pre]);
    }
  }, maxrcY);
  maxrcY = (maxrcY * 1.2).toFixed(2);
  minrcY = (minrcY * 0.8).toFixed(2);
  return {
    minY,
    maxY,
    maxrcY,
    minrcY
  };
};

const labelLayoutFn = (data: any, title: string) => {
  const { minY, maxY, minrcY, maxrcY } = getMinYMaxY(data);
  const options: UtilsEChartsOption = {
    title: {
      text: "",
      textStyle: {
        fontSize: 16
      },
      // subtext: "曲线标题",
      left: "left",
      top: "top",
      padding: [10, 0, 0, 20]
    },
    tooltip: {
      trigger: "axis",
      confine: true,
      axisPointer: {
        type: "shadow"
      },
      textStyle: {
        align: "left"
      },
      formatter: params => {
        let relVal = params[0].name;
        for (let i = 0; i < params.length; i++) {
          params[i].value = new Intl.NumberFormat("en-US").format(params[i].value);
          if (params[i].value == "NaN") {
            params[i].value = "-";
          }
          relVal += `<br/>${params[i].marker} ${params[i].seriesName} ${params[i].value} ${params[i].seriesName === "预测误差" ? "%" : getUnit.value}`;
        }
        return relVal;
      }
    },
    legend: {
      // type: "scroll",
      // pager: {
      //   orient: "vertical",
      //   pageButtonItemGap: 5
      // },
      // data: props.areaList.map((item: any) => item.name),
      data: ["实际", "预测", "预测误差"],
      selected: {
        实际: true,
        预测: true,
        预测误差: false
      },
      top: 15
      // data: ["实际", "预测"]
      // orient: "horizontal"
    },
    grid: {
      left: "0",
      top: "15%",
      right: "0",
      bottom: "0",
      containLabel: true
    },
    // dataset: {
    //   source: arr
    // },
    xAxis: {
      type: "category",
      data: (title.includes("年") ? data.abscissa.map(e => e) : data.abscissa.map(e => e.substring(3))) || []
    },
    yAxis: [
      {
        type: "value",
        name: `单位：${getUnit.value}`,
        alignTicks: true,
        nameTextStyle: {
          align: "left"
        },
        axisLine: {
          show: true,
          lineStyle: {
            width: 1
          }
        },
        axisLabel: {
          formatter: function (value) {
            return Number(value).toFixed(2);
          }
        },
        min: minY,
        max: maxY
      },
      {
        type: "value",
        // name: `%`,
        // position: "left",
        axisLabel: {
          formatter: function (value) {
            return Number(value).toFixed(2) + "%";
          }
        },
        alignTicks: true,
        // offset: 50,
        axisLine: {
          show: true,
          lineStyle: {
            width: 1
          }
        },
        min: minrcY,
        max: maxrcY
      }
    ],
    series: [
      {
        name: "实际",
        type: "bar",
        barWidth: 16,
        itemStyle: {
          color: "#3B82F6"
        },
        yAxisIndex: 0,
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        },
        data: data.kwhCoordinate ? data.kwhCoordinate.map(v => (v === null ? v : Number(v))) : []
      },
      {
        name: "预测",
        type: "bar",
        barWidth: 16,
        yAxisIndex: 0,
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        },
        itemStyle: {
          color: "#603BF6"
        },
        data: data.kwhPredictCoordinate ? data.kwhPredictCoordinate.map(v => (v === null ? v : Number(v))) : []
      },
      {
        name: "预测误差",
        type: "line",
        yAxisIndex: 1,
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        },
        itemStyle: {
          color: "#FFCA45"
        },
        data: data.radioCoordinate ? data.radioCoordinate.map(v => (v === null ? v : Number(v))) : []
        // data: [11, 12, 14, 16, 8, 9, 15, 7, 22, 13, 7, 20]
      }
    ]
  };
  return options;
};
// 总排名
const labelLayoutAreaFn = async () => {
  const title = "";
  const param = {
    timeFrame: queryParams.value.dateRangeItem,
    month: queryParams.value.month,
    energyType: queryTypeParams.value.energyType
  };
  const res: any = await getCostPredictData(param);
  if (res.annualEnergyConsumptionTrend) {
    actualDataList.value = res.annualEnergyConsumptionTrend.actualTrendNodeList?.map(item => {
      item.icon = getIcon.value;
      return item;
    });
    predictDataList.value = res.annualEnergyConsumptionTrend.predictTrendNodeList?.map(item => {
      item.icon = getIcon.value;
      return item;
    });
    annualOverview.value = res.annualOverview;
    monthlyDetails.value = res.monthlyDetails;
    let year = new Date().getFullYear();
    if (Number(queryParams.value.dateRangeItem) === year) {
      isCurrentYear.value = true;
    } else {
      isCurrentYear.value = false;
      predictDataList.value.pop();
    }
  } else {
    actualDataList.value = [];
    predictDataList.value = [];
    annualOverview.value = null;
    monthlyDetails.value = null;
  }

  const data = [];
  if (res.annualOverview && res.annualOverview.annualGraph) {
    yearOptions.value = res.annualOverview.annualGraph ? labelLayoutFn(res.annualOverview.annualGraph, "年") : {};
  }
  if (res.monthlyDetails && res.monthlyDetails.monthGraph) {
    monthOptions.value = labelLayoutFn(res.monthlyDetails.monthGraph, "月");
  }
  midKey.value = Date.now();
};
interface queryForm {
  dateRangeItem?: string;
  level?: string;
  startTime?: string;
  endTime?: string;
  month?: string | number;
}

const queryParams = ref<queryForm>({
  dateRangeItem: "",
  month: new Date().getMonth() + 1
});

const queryTypeParams = ref({
  energyType: 1
});

const loading = ref(false);

const handleChangeTypeFn = (val: number) => {
  queryTypeParams.value.energyType = val;
  labelLayoutAreaFn();
};

const factoryName = ref("");
/** 搜索按钮操作 */
function handleQuery() {
  labelLayoutAreaFn();
}
/** 重置按钮操作 */
function resetQuery() {
  initQuery();
}

// 默认查询条件
const initQuery = () => {
  queryParams.value.dateRangeItem = proxy.parseTime(new Date(), "{y}");
  labelLayoutAreaFn();
};
const changeMonth = () => {
  handleQuery();
};
/** 导出按钮操作 */
const handleDown = async val => {
  if (val == "year") {
    proxy.download("post", "/energy/energyPredictionStatistics/viewAnnualCost/download", annualOverview.value, `年度总览.xlsx`);
  }
  if (val == "month") {
    proxy.download("post", "/energy/energyPredictionStatistics/viewMonth/download", monthlyDetails.value, `月度明细.xlsx`);
  }
};

onMounted(async () => {
  initQuery();
  systemList.value = await queryDictData({ typeCode: "factoryArea" });
});
</script>

<style lang="scss" scoped>
.energy_consume {
  display: flex;
  flex-direction: column;
  gap: 16px;
  justify-content: flex-start;

  :deep(.px-empty .px-empty__image) {
    display: none !important;
  }

  .top_query {
    display: flex;
    flex-flow: row nowrap;
    width: 100%;
    min-width: 1300px;
    height: auto;
    padding: 16px 24px;
    line-height: 44px;
    background: #fff;
    border-radius: 4px;

    .tabs {
      display: flex;
      align-items: center;
      justify-content: center;
      line-height: 1;

      /*
      * tab样式
      */
      .tabSwitch {
        padding: 4px;
        margin-right: 20px;
        background-color: #f4f4f4;
        border-radius: 4px;

        :deep(.px-radio-button__inner) {
          background-color: #f4f4f4;
          border: none;
        }

        :deep(.is-active) {
          border: none;

          .px-radio-button__inner {
            background-color: var(--px-color-primary);
            border-radius: 4px;
          }
        }
      }
    }

    .px-form-item {
      margin-bottom: 0;
    }
  }

  .mid-bord {
    width: 100%;
    min-width: 1300px;
    // height: 167px;
    background: #fff;
    border-radius: 4px;
  }

  .btn-con {
    display: flex;
    gap: 16px;
    justify-content: space-between;

    .btn-bord {
      position: relative;
      width: 100%;
      min-width: 1300px;
      height: 515px;
      background: #fff;
      border-radius: 4px;

      .rightBox {
        position: absolute;
        top: 16px;
        right: 20px;

        .selectMonth {
          width: 80px;
          margin-right: 15px;
        }
      }
    }
  }
}
</style>
